'use client'

import { useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useAuth } from '@/contexts/AuthContext'
import { Loader2 } from 'lucide-react'
import { safeRouterPush } from '@/lib/utils/safeStateUpdate'

interface ProtectedRouteProps {
  children: React.ReactNode
  requiredRole?: 'ADMIN' | 'EDITOR' | 'VIEWER'
}

export function ProtectedRoute({ children, requiredRole }: ProtectedRouteProps) {
  const { user, isLoading, isAuthenticated } = useAuth()
  const router = useRouter()

  // 使用 useCallback 来避免不必要的重新渲染
  const redirectToLogin = useCallback(() => {
    if (!isLoading && !isAuthenticated) {
      safeRouterPush(router.push, '/login')
    }
  }, [isLoading, isAuthenticated, router])

  const redirectToDashboard = useCallback(() => {
    if (!isLoading && isAuthenticated && requiredRole && user?.role !== requiredRole) {
      safeRouterPush(router.push, '/')
    }
  }, [isLoading, isAuthenticated, user?.role, requiredRole, router])

  useEffect(() => {
    redirectToLogin()
  }, [redirectToLogin])

  useEffect(() => {
    redirectToDashboard()
  }, [redirectToDashboard])

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600 mx-auto mb-4" />
          <p className="text-gray-600">正在验证身份...</p>
        </div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return null
  }

  if (requiredRole && user?.role !== requiredRole) {
    return null
  }

  return <>{children}</>
}
